package org.jeecg.cn.edu.scau.vm.node.factory;

import ch.ethz.ssh2.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * SSH连接工厂
 */
public class SSHSessionFactory {

    private static final Logger logger = LoggerFactory.getLogger(SSHSessionFactory.class);


    public static Connection getConnection(String ipAddress,
                                           String username,
                                           String password,
                                           Integer port) {
        if (Objects.isNull(port) || port < 0 || port > 65535) {
            port = 22;
        }
        Connection connection = new Connection(ipAddress, port);
        try {
            connection.connect();
            if (!connection.authenticateWithPassword(username, password)) {
                logger.info("认证失败");
                throw new RuntimeException("请检查用户名、密码、端口等基本信息是否正确");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return connection;
    }
}
